package com.plum.admin.modules.sys.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.plum.admin.common.annotation.Log;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.enums.LogType;
import com.plum.admin.common.util.PasswordUtil;
import com.plum.admin.common.util.R;
import com.plum.admin.common.util.RedisCache;
import com.plum.admin.common.util.SecurityUtil;
import com.plum.admin.common.vo.EmailValidate;
import com.plum.admin.modules.sys.dto.UserDTO;
import com.plum.admin.modules.sys.entity.SysUser;
import com.plum.admin.modules.sys.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.plum.admin.base.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 子丶沫
 * @since 2021-08-13
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户管理")
@Slf4j
@RequiredArgsConstructor
public class SysUserController extends BaseController {

    private final ISysUserService userService;
    private final SecurityUtil securityUtil;
    private final RedisCache redisCache;
    @ApiOperation("分页查询用户")
    @GetMapping
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @Log(type = LogType.OPERATION,title = "分页查询用户")
    public R<Object> queryUserList(Integer pageNo, Integer pageSize, UserDTO userDTO){
        IPage<SysUser> page = userService.queryUserList(new Page<>(pageNo, pageSize), userDTO);
        return R.ok(page);
    }
    @ApiOperation("获取当前登录用户信息")
    @GetMapping("userInfo")
    @Log(type = LogType.OPERATION,title = "获取当前登录用户信息")
    public R<Object> info(){
        String username = securityUtil.getUser().getUsername();
        return R.ok(userService.findByUsername(username));
    }
    @ApiOperation("禁用用户")
    @PreAuthorize("hasAnyAuthority('sys:user:disabled')")
    @PostMapping("/disabledUser/{id}")
    @Log(type = LogType.OPERATION,title = "禁用用户")
    public R<Object> disabledUser(@PathVariable("id") String id){
        return R.ok(userService
                .update(Wrappers.<SysUser>lambdaUpdate()
                        .set(SysUser::getLockFlag, Constant.USER_STATUS_LOCK).eq(SysUser::getId,id)));
    }
    @ApiOperation("启用用户")
    @PreAuthorize("hasAnyAuthority('sys:user:enable')")
    @PostMapping("/enabledUser/{id}")
    @Log(type = LogType.OPERATION,title = "启用用户")
    public R<Object> enabledUser(@PathVariable("id") String id){
        return R.ok(userService
                .update(Wrappers.<SysUser>lambdaUpdate()
                        .set(SysUser::getLockFlag, Constant.USER_STATUS_NORMAL).eq(SysUser::getId,id)));
    }
    @ApiOperation("删除用户")
    @PreAuthorize("hasAnyAuthority('sys:user:delete')")
    @DeleteMapping
    @Log(type = LogType.OPERATION,title = "删除用户")
    public R<Object> deleteUser(String ids){
        List<String> idList = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        for (String id : idList) {
            if(Constant.ADMIN_USER_ID.equals(id)){
                return R.error("不能删除超级管理员");
            }
        }
        return R.ok(userService.deleteUser(idList));
    }
    @ApiOperation("添加用户")
    @Log(type = LogType.OPERATION,title = "添加用户")
    @PreAuthorize("hasAnyAuthority('sys:user:insert')")
    @PostMapping
    public R<Object> insertUser(@RequestBody UserDTO userDTO){
        return R.ok(userService.insertUser(userDTO));
    }

    @ApiOperation("修改用户")
    @PreAuthorize("hasAnyAuthority('sys:user:edit')")
    @PutMapping
    @Log(type = LogType.OPERATION,title = "修改用户")
    public R<Object> updateUser(@RequestBody UserDTO userDTO){
        return R.ok(userService.updateUser(userDTO));
    }

    @ApiOperation("修改当前账号信息")
    @PreAuthorize("hasAnyAuthority('sys:user:edit')")
    @PutMapping("/editUser")
    @Log(type = LogType.OPERATION,title = "修改当前账号信息")
    public R<Object> editUser(@RequestBody SysUser user){
        return R.ok(userService.updateById(user));
    }
    @ApiOperation("校验登陆账号唯一性")
    @GetMapping("/checkUsername")
    @Log(type = LogType.OPERATION,title = "校验登陆账号唯一性")
    public R<Object> checkUsername(String username,String oldUsername){
        if(StrUtil.isNotBlank(oldUsername)){
            if(username.equals(oldUsername)){
                return R.ok(false);
            }
        }
        return R.ok(userService.checkUsername(username));
    }
    @ApiOperation("校验手机号码唯一性")
    @GetMapping("/checkMobile")
    @Log(type = LogType.OPERATION,title = "校验手机号码唯一性")
    public R<Object> checkMobile(String mobile,String oldMobile){
        if(StrUtil.isNotBlank(oldMobile)){
            if(mobile.equals(oldMobile)){
                return R.ok(false);
            }
        }
        return R.ok(userService.list(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getPhone,mobile)).size()>0);
    }
    @ApiOperation("唯一性校验")
    @GetMapping("/checkUniqueness")
    @Log(type = LogType.OPERATION,title = "唯一性校验")
    public R<Object> checkUniqueness(String mobile,String email,String username){
        return R.ok(userService.list(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getPhone,mobile).or().eq(SysUser::getEmail,email).or().eq(SysUser::getUsername,username)).size()>0);
    }
    @ApiOperation("手机号码找回密码")
    @PostMapping("/findPassByMobile")
    @Log(type = LogType.OPERATION,title = "手机号码找回密码")
    public R<Object> findPassByMobile(String mobile,String smsCode,String password){
        SysUser sysUser = userService.findByUserMobile(mobile);
        if(ObjectUtil.isNull(sysUser)){
            return R.error("手机号码不存在");
        }
        if(StrUtil.isBlank(smsCode)){
            return R.error("验证码为空");
        }
        Object key = redisCache.getCacheObject(Constant.SMS_PRE + mobile);
        if(ObjectUtil.isNull(key)){
            return R.error("验证码已失效");
        }
        String code = String.valueOf(key);
        if(!code.equalsIgnoreCase(smsCode)){
            return R.error("验证码错误");
        }
        sysUser.setPassword(PasswordUtil.encodePassword(password));
        redisCache.deleteObject(Constant.SMS_PRE + mobile);
        return R.ok(userService.updateById(sysUser));
    }
    @ApiOperation("邮件找回密码")
    @PostMapping("/findPassByEmail")
    @Log(type = LogType.OPERATION,title = "邮件找回密码")
    public R<Object> findPassByEmail(String email,String code,String password){
        SysUser sysUser = userService.findByEmail(email);
        if(ObjectUtil.isNull(sysUser)){
            return R.error("邮箱地址不存在");
        }
        if(StrUtil.isBlank(code)){
            return R.error("验证码为空");
        }
        Object key = redisCache.getCacheObject(Constant.PRE_EMAIL + email);
        if(ObjectUtil.isNull(key)){
            return R.error("验证码已失效");
        }
        EmailValidate emailValidate = new Gson().fromJson(String.valueOf(key), EmailValidate.class);
        if(!code.equalsIgnoreCase(emailValidate.getCode())){
            return R.error("验证码错误");
        }
        sysUser.setPassword(PasswordUtil.encodePassword(password));
        redisCache.deleteObject(Constant.PRE_EMAIL + email);
        return R.ok(userService.updateById(sysUser));
    }
    @ApiOperation("注册登录账号")
    @PostMapping("/register")

    public R<Object> register(@RequestBody UserDTO userDTO,@PathVariable String smsCode){
        return R.ok(userService.register(userDTO,smsCode));
    }
    @ApiOperation("校验密码是否正确")
    @PostMapping("checkPasswd")
    @Log(type = LogType.OPERATION,title = "校验密码是否正确")
    public R<Object> checkPasswd(String password){
        SysUser user = securityUtil.getUser();
        return R.ok(PasswordUtil.validaPassword(password,user.getPassword()));
    }
    @ApiOperation("修改密码")
    @PostMapping("updatePassword")
    @Log(type = LogType.OPERATION,title = "修改密码")
    public R<Object> updatePassword(String password, HttpServletRequest request){
        SysUser user = securityUtil.getUser();
        return R.ok(userService.updatePassword(user,password,request));
    }
    @ApiOperation("修改手机号码")
    @PostMapping("/editMobile")
    @Log(type = LogType.OPERATION,title = "修改手机号码")
    public R<Object> editMobile(String mobile,String smsCode){
        String code = redisCache.getCacheObject(Constant.SMS_PRE + mobile);
        if(StrUtil.isBlank(smsCode)){
            return R.error("验证码为空");
        }
        if(StrUtil.isBlank(code)){
            return R.error("验证码已失效");
        }
        if(!code.equals(smsCode)){
           return R.error("验证码错误");
        }
        SysUser user = securityUtil.getUser();
        user.setPhone(mobile);
        return R.ok(userService.updateById(user));
    }
    @ApiOperation("修改邮箱")
    @PostMapping("/editEmail")
    @Log(type = LogType.OPERATION,title = "修改邮箱")
    public R<Object> editEmail(String email,String emailCode){
        String value=redisCache.getCacheObject(Constant.PRE_EMAIL+email);
        if(StrUtil.isBlank(value)){
            return R.error("验证码已失效");
        }
        EmailValidate emailValidate = new Gson().fromJson(value, EmailValidate.class);
        if(!"修改邮箱".equals(emailValidate.getOperation())){
            return R.error("验证码已失效");
        }
        if(StrUtil.isBlank(emailValidate.getCode())){
            return R.error("验证码已失效");
        }
        if(!emailCode.equals(emailValidate.getCode())){
            return R.error("验证码错误");
        }
        SysUser user = securityUtil.getUser();
        user.setEmail(email);
        return R.ok(userService.updateById(user));
    }
}
